/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.warehouse.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.warehouse.entity.Material;
import com.thinkgem.jeesite.modules.warehouse.entity.MaterialRecord;

import freemarker.core._RegexBuiltins.replace_reBI;

import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.warehouse.dao.MaterialRecordDao;

/**
 * MaterialRecordService
 * 
 * @author qrg
 * @version 2017-03-27
 */
@Service
@Transactional(readOnly = true)
public class MaterialRecordService extends CrudService<MaterialRecordDao, MaterialRecord> {

	@Autowired
	private MaterialService materialService;
	
	@Autowired
	private MaterialRecordDao materialRecordDao;

	public MaterialRecord get(String id) {
		return super.get(id);
	}

	public List<MaterialRecord> findList(MaterialRecord materialRecord) {
		return super.findList(materialRecord);
	}

	public Page<MaterialRecord> findPage(Page<MaterialRecord> page, MaterialRecord materialRecord) {
		//return super.findPage(page, materialRecord);
		materialRecord.getSqlMap().put("dsf", dataScopeFilter(materialRecord.getCurrentUser(), "o11", "u"));
		materialRecord.setPage(page);
		page.setList(materialRecordDao.findList(materialRecord));
		return page;
	}

	@Transactional(readOnly = false)
	public void save(MaterialRecord materialRecord) {

		// 设置当前记录的OFFICE
		Office office = UserUtils.getUser().getOffice();
		materialRecord.setOffice(office);
		
		//获取是否是新增加的materialRecord
		double oldStock = 0.0;
		String oldInout = null;
		double stock = materialRecord.getCount();
		if(!materialRecord.getIsNewRecord()){
			MaterialRecord oldMaterialRecord = get(materialRecord.getId());
			oldStock = oldMaterialRecord.getCount();
			oldInout = oldMaterialRecord.getInOut();
			
			if(oldInout.equals("INBOUND")){
				if(materialRecord.getInOut().equals("INBOUND")){
					stock -= oldStock;
				}else{
					stock += oldStock;
				}			
			}
			else{
				if(materialRecord.getInOut().equals("INBOUND")){
					stock += oldStock;
				}else{
					stock -= oldStock;
				}			
			}
		}
		
		// 保存当前物料记录
		super.save(materialRecord);

		// 将出库数据更新回到物料表
		Material material = materialService.get(materialRecord.getMaterial().getId());
		materialService.updateStock(material, materialRecord.getInOut(), stock);

	}

	@Transactional(readOnly = false)
	public void delete(MaterialRecord materialRecord) {
		super.delete(materialRecord);
	}

}